/**
 * 签到页面
 * author:zhangjlt
 * date:2017年3月13日11:30:42
 */
;
define(function(require, exports, module) {
	var wechat = require("wechat");
	var template = require("template");
	var glD = require("lib/glDatePicker");
	var signIn = {
		currentPage: 1,
		pageSize: 10,
		loadedAllFlag: false,
		loadingFlag: false,
		data: {},
		/**
		 * bindEvent 页面事件
		 */
		bindEvent: function() {
			//返回
			$("#return_signIn").unbind().on("click", function() {
				window.location.href = "#home";
			});
			$(document).off("click", '#signinBtn_signIn').on("click", '#signinBtn_signIn', function() {
				if(!signIn.loadingFlag) {
					signIn.getSignResult();
				} else {
					return;
				}

			});
		},
		/**
		 * 进行页面路由监听配置
		 * 
		 */
		bindRout: function() {
			//公共页面监听路由
			Path.map("#home").to(function() {
				//返回首页
				common.loadPage({
					pageUrl: "html/index.html",
					reload: true,
					from: "left"
				});
			});
			//公共页面监听路由
			Path.map("").to(function() {
				//返回首页
				common.loadPage({
					pageUrl: "html/index.html",
					reload: true,
					from: "left"
				});
			});
			Path.listen();
		},
		getSignResult: function() {
			var param = {
				"openId": window.localStorage.getItem("openId"),
				"appId": window.localStorage.getItem("appId"),
			};
			signIn.loadingFlag = true;
			common.loadData({
				url: "/wxmember/service/getSignResult",
				param: param,
				successCallBack: function(res) {
					signIn.loadingFlag = false;
					if(res.status == 0) {

						common.showTip({
							content: "签到成功，积分+" + res.data.point.toString()
						});
						signIn.loadData();

					} else {
						common.showTip({
							content: res.message
						});
						signIn.loadData();
					}

				}, //回调函数
				dataSource: "getSignList",
				cache: false

			});
		},
		/**
		 * 页面数据加载
		 */
		loadData: function() {
			//日历显示
			var myDate = new Date();
			var Month = myDate.getMonth() + 1;
			var days = getDaysInOneMonth(Month);
			var nowData = myDate.getFullYear() + '-' + Month + '-' + days;
			var oldData = myDate.getFullYear() + '-' + Month + '-01';
			var endtime = nowData + " 23:59:59";
			var begaintime = oldData + " 00:00:00";
			var _this = this;
			var param = {
				"openId": window.localStorage.getItem("openId"),
				"appId": window.localStorage.getItem("appId"),
				"endtime": endtime,
				"begaintime": begaintime
			};
			common.loadData({
				url: "/wxmember/service/getSignList",
				param: param,
				successCallBack: _this.getSignListCallBack, //回调函数
				dataSource: "getSignList",
				loadAll: _this.loadedAllFlag, //标识是不加载全部
				cache: false
			});

		},
		pullUpActionCallBack: function() {
			signIn.currentPage += 1;
			signIn.loadData();
		},
		//callback function
		getSignListCallBack: function(json) {
			console.log("调用后台ajax返回值为：" + JSON.stringify(json));
			if(json.status == "0") {
				//先检查数据初始化数据是否已取得，如果没有则提示，然后调用后台加载数据
				//当前选中日期 
				var date = new Date();
				var month = date.getMonth() + 1;
				var strDate = date.getDate();
				$("#currentSelectDateId").val(month + "_" + strDate + "_parent");
				//默认赋值
				$("#hideDate").val(getNowFormatDate("date"));
				if(month >= 0 && month <= 9) {
					month = "0" + month;
				}
				if(strDate >= 0 && strDate <= 9) {
					strDate = "0" + strDate;
				}
				$("#appDateTime").html(getMonthStartDate().substring(0, 7));

				if(json.data && json.data.list && json.data.list.length > 0) {
					queryAttendanceByDataZoneSucess(json.data.list);
					showDetaiofOneDay(month, strDate);
					$("#totalAttendance").text(json.data.totalAttendance);
					$("#continuousSign").text(json.data.continuousSign);
				} else {
					if(signIn.currentPage == 1) {
						var html = '<li>未查询到签到活动说明</li>';
						$("#main_signIn2").html(html);
						var html2 = '<li>未查询到签到记录信息</li>';
						$("#main_signIn").html(html2);
					} else {
						//两个部分共同控制加载全部
						common.loadedAll();
						//						signIn.loadedAllFlag = true;
					}
				}
				//iscroll滚动加入
				var iscroll = require("iscroll");
				common.initIscroll({
					container: "iscrollContent_signIn",
					showScrollBar: false,
					loadAll: signIn.loadedAllFlag
				});
			} else {
				if(signIn.currentPage == 1) {
					var html = '<li>未查询到签到活动说明</li>';
					$("#main_signIn2").html(html);
					var html2 = '<li>未查询到签到记录信息</li>';
					$("#main_signIn").html(html2);
				}

				common.showTip({
					content: json.message
				});
			}

		},
		/**
		 * each page init mothed
		 */
		initialize: function() {
			$('#example_signIn').glDatePicker({
				showAlways: true,
				format: 'yyyy-mm-dd'
			});
			this.loadData();
			//事件绑定
			this.bindEvent();
			//路由绑定
			this.bindRout();
		}
	};

	module.exports = signIn;
});
//获取当前的日期时间 格式“yyyy-MM-dd” 2:获取当前的日期时间 格式“yyyy-MM-dd HH:MM:SS”
function getNowFormatDate(type) {
	var date = new Date();
	var seperator1 = "-";
	var seperator2 = ":";
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if(month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if(strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	if(type != "date") {
		return date.getFullYear() + seperator1 + month + seperator1 + strDate +
			" " + date.getHours() + seperator2 + date.getMinutes() +
			seperator2 + date.getSeconds();
	} else {
		return date.getFullYear() + seperator1 + month + seperator1 + strDate;
	}

}

function showDetaiofOneDay(month, strDate) {
	$(".qd_list").html("");
	var array = [];
	if(month && strDate) {
		//判断考勤是都正常，并在图上进行标识出来
		for(var i = 0; i < currentPageJson.queryAttendance.length; i++) {
			//取得日期
			var item = currentPageJson.queryAttendance[i];
			var attendanceDate_orange = item.time;
			var attendanceMessage_red = "";
			var monthStr = attendanceDate_orange.month;
			var dayStr = attendanceDate_orange.day;
			if(monthStr == month && strDate == dayStr) {
				array.push(item);
			}
		}
		var html = "";
		if(array.length > 0) {
			for(var j = 0; j < array.length; j++) {
				var itemdetail = array[j];
				html += '<li><div class="rec_left">' + itemdetail.time.date + "签到" + itemdetail.times + "次" +
					'</div><div class="rec_right">+' + itemdetail.points + '</div></li>';
			}
		} else {
			html = '<li><div class="rec_left">本日没有签到</div></li>';
		}
		$(".qd_list").html(html);

	}
	common.initIscroll({
		container: "iscrollContent_signIn",
		showScrollBar: false
	});
}
//单击左右选择的时候，查询出勤情况
function getAttendanceInfo(type) {
	var maxDays = getDaysInOneMonth(type);
	var year = $("#hideYear").val();
	var month = $("#hideMonth").val();

	if(month < 10) {
		month = "0" + month;
	}

	//console.log("type====" + type + ",year + month===" + year + month);
	//查询考勤情况，根据计算的月份
	queryAttendanceByDataZone(year + "-" + month + "-01", year + "-" + month + "-" + maxDays);

	//console.log(year + "-" + month);
	$("#appDateTime").html(year + "-" + month);

}
//获得某月的天数     
function getMonthDays(myMonth) {
	var begaintime = nowData + " 23:59:59";
	var endtime = oldData + " 00:00:00";
	var now = new Date(); //当前日期     
	var nowYear = now.getYear(); //当前年     
	nowYear += (nowYear < 2000) ? 1900 : 0; //  
	var monthStartDate = new Date(nowYear, myMonth, 1);
	var monthEndDate = new Date(nowYear, myMonth + 1, 1);
	var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
	return days;
}
//计算当前月份的最大天数
function getDaysInOneMonth(type) {
	var year = $("#hideYear").val();
	var month = $("#hideMonth").val();

	month = parseInt(month, 10);
	//console.log("year ===" + year + ",month===" + month);

	var d = new Date(year, month, 0);
	//alert(d.getDate());
	return d.getDate();
}
/** 
 * 获取本周、本季度、本月、上月的开端日期、停止日期 
 */
//获得本月的开始日期     
function getMonthStartDate() {
	var now = new Date(); //当前日期   
	var nowMonth = now.getMonth(); //当前月     
	var nowYear = now.getYear(); //当前年 
	nowYear += (nowYear < 2000) ? 1900 : 0; //  
	var monthStartDate = new Date(nowYear, nowMonth, 1);
	return formatDate(monthStartDate);
}

//获得本月的结束日期     
function getMonthEndDate() {
	var now = new Date(); //当前日期   
	var nowMonth = now.getMonth(); //当前月     
	var nowYear = now.getYear(); //当前年   
	nowYear += (nowYear < 2000) ? 1900 : 0; //  
	var monthEndDate = new Date(nowYear, nowMonth, getMonthDays(nowMonth));
	return formatDate(monthEndDate);
}
//格式化日期：yyyy-MM-dd     
function formatDate(date) {
	var now = new Date(date); //当前日期    
	var nowYear = now.getYear(nowYear); //当前年 
	nowYear += (nowYear < 2000) ? 1900 : 0; //  
	var myyear = nowYear;
	var mymonth = date.getMonth() + 1;
	var myweekday = date.getDate();

	if(mymonth < 10) {
		mymonth = "0" + mymonth;
	}
	if(myweekday < 10) {
		myweekday = "0" + myweekday;
	}
	return(myyear + "-" + mymonth + "-" + myweekday);
}

function string2Json(s) {
	var newstr = "";
	//替换\r
	s = s.replace(/\\r/g, "");
	//替换\n
	s = s.replace(/\\n/g, "")
	return s;
}
//取得相应月份的出勤情况，默认为当前月
function queryAttendanceByDataZone(beginDate, endDate) {
	var endtime = endDate + " 23:59:59";
	var begaintime = beginDate + " 00:00:00";
	var param = {
		"openId": window.localStorage.getItem("openId"),
		"appId": window.localStorage.getItem("appId"),
		"endtime": endtime,
		"begaintime": begaintime

	};
	common.loadData({
		url: "/wxmember/service/getSignList",
		param: param,
		successCallBack: function(json) {

			console.log("调用后台ajax返回值为：" + JSON.stringify(json));
			if(json.status == "0") {

				if(json.data && json.data.list && json.data.list.length > 0) {
					queryAttendanceByDataZoneSucess(json.data.list);
					$("#totalAttendance").text(json.data.totalAttendance);
					$("#continuousSign").text(json.data.continuousSign);
				} else {
					showDetaiofOneDay();
				}
			} else {

				common.showTip({
					content: json.message
				});
			}

		}, //回调函数
		dataSource: "getSignList",
		cache: false
	});
}
//取得相应月份的出勤情况，默认为当前月成功处理页面
function queryAttendanceByDataZoneSucess(result) {
	//	result = strToJson(result);
	//放在大变量中，后面点击等操作不再调用接口
	currentPageJson.queryAttendance = result;
	console.log("相应月份的出勤情况，默认为当前月===" + JSON.stringify(result));
	//赋值
	var year = $("#hideYear").val();
	var month = $("#hideMonth").val();

	if(month < 10) {
		month = "0" + month;
	}
	$("#appDateTime").val(year + "-" + month);
	showAttendanceInCalander_Orange(result);
}
//字符串转换为Json对象
function strToJson(str) {
	var json = eval('(' + str + ')');
	return json;
}
//用户点击日历后，去后台查询当天的考勤状况
function queryAttendanceDayDetails(attendanceDate) {
	//先显示当前日期
	var currentDate = attendanceDate;
	//	//拼结显示日期
	//	$("#currentDateSpan").html(currentDate.substring(5,7) + "月" + currentDate.substring(8,10) + "日");
	// 	var foot = strToJson(currentPageJson.initData.foot);
	//	var queryAttendanceDayDetails = {datestr:currentDate,timezone:"",userid:foot.userid};
	//	//用户点击日历后，去后台查询当天的考勤状况
	//	commonAjaxFunction("queryAttendanceDayDetails",queryAttendanceDayDetails,"queryAttendanceDayDetailsSucess","showErrorInfo");
}
var currentPageJson = {};
//把数据显示在日历控件上面
function showAttendanceInCalander_Orange(list) {
	//判断考勤是都正常，并在图上进行标识出来
	for(var i = 0; i < list.length; i++) {
		//取得日期
		var item = list[i];
		var attendanceDate_orange = list[i].time;;
		var attendanceMessage_red = "";
		var monthStr = parseInt(attendanceDate_orange.month);
		var dayStr = parseInt(attendanceDate_orange.day);
		var circleObj = $("#" + monthStr + "_" + dayStr);
		circleObj.css("background-color", "#fc9400");

	}

}

//改变选中的日历的背景色
function selectedAttendanceChangeColor() {
	//已经选中部分重新变色
	var clickObjId = $("#currentSelectDateId").val();
	//console.log("clickObjId======" + clickObjId);
	if(clickObjId != "") {
		//对应圆圈的id  _parent deleted
		var clickCirclObjId = clickObjId.substring(0, clickObjId.length - 7);
		//动态改变背景色
		//如果圆圈背景色为红色，则证明是有异常考勤的点
		var circlePointBackgroundCss = $("#" + clickCirclObjId).css("background-color");
		//console.log("clickCirclObjId==" + clickCirclObjId + ",circlePointBackgroundCss===" + circlePointBackgroundCss);
		if(circlePointBackgroundCss == "rgb(255, 0, 0)") {
			$("#" + clickCirclObjId).css("background-color", "#fff");
			//父层加上红色背景
			$("#" + clickObjId + " .circle").css("background", "red");
		}
		if(circlePointBackgroundCss == "rgb(252, 148, 0)") {
			$("#" + clickCirclObjId).css("background-color", "#fff");
			//父层加上橙色色背景
			$("#" + clickObjId + " .circle").css("background", "#fc9400");
		}
	}
}